<!DOCTYPE html>
<html lang="">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">

    
      <link rel="icon" href="/favicon.png" />
    

    <title>
        
          CODE&#39;NOTE
        
    </title>

    <!-- Spectre.css framework -->
    <link href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre.min.css" rel="stylesheet">
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre-exp.min.css" rel="stylesheet">
    <link href="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/spectre.css/0.5.9/spectre-icons.min.css" rel="stylesheet">

    <!-- theme css & js -->
    
<link rel="stylesheet" href="/css/book.css">

    
<script src="/js/book.js"></script>


    <!-- tocbot -->
    <script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/tocbot/4.18.2/tocbot.min.js"></script>
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/tocbot/4.18.2/tocbot.css" rel="stylesheet">
    
    <!-- katex -->    
    <link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/KaTeX/0.15.2/katex.min.css" rel="stylesheet">

    
    
<script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/zooming/2.1.1/zooming.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const zooming = new Zooming()
    zooming.listen('.book-content img')
})
</script>

<meta name="generator" content="Hexo 6.1.0"></head>

<body>

<div class="book-container">
  <div class="book-sidebar">
    <div class="book-brand">
  <a href="/">
    <img src="/favicon.png">
    <span>CODE&#39;NOTE</span>
  </a>
</div>
    <div id="menu" class="book-menu hide">
  <h2 id="☘️-Home">☘️ <a href="/">Home</a></h2>
<h2 id="Go">Go</h2>
<ul>
<li><a href="/go/01%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA">0.1 开发环境搭建</a></li>
<li><a href="/go/02%E5%8F%98%E9%87%8F%E5%92%8C%E5%B8%B8%E9%87%8F">0.2 变量和常量</a></li>
<li><a href="/go/03%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B">0.3 基本数据类型</a></li>
<li><a href="/go/04%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E5%92%8C%E8%BF%90%E7%AE%97%E7%AC%A6">0.4 流程控制和运算符</a></li>
<li><a href="/go/05%E6%95%B0%E7%BB%84">0.5 数组</a></li>
<li><a href="/go/06%E5%88%87%E7%89%87">0.6 切片</a></li>
<li><a href="/go/07map">0.7 map</a></li>
<li><a href="/go/08%E5%87%BD%E6%95%B0">0.8 函数</a></li>
<li><a href="/go/09%E6%8C%87%E9%92%88">0.9 指针</a></li>
<li><a href="/go/10%E5%8F%8D%E5%B0%84">1.0 反射</a></li>
<li><a href="/go/11%E7%BB%93%E6%9E%84%E4%BD%93">1.1 结构体</a></li>
<li><a href="/go/12%E6%8E%A5%E5%8F%A3">1.2 接口</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/goroutine">1.3 goroutine</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/channel">1.4 channel</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/%E5%B9%B6%E5%8F%91%E5%AE%89%E5%85%A8%E5%92%8C%E9%94%81">1.5 并发安全和锁</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C">1.6 原子操作</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/GPM%E5%8E%9F%E7%90%86%E4%B8%8E%E8%B0%83%E5%BA%A6">1.7 GPM与调度分析</a></li>
<li><a href="/go/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/CSP%E5%B9%B6%E5%8F%91%E6%A8%A1%E5%9E%8B">1.8 CSP并发模型</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/fmt">标准库fmt</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/flag">标准库flag</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/time">标准库time</a></li>
<li><a href="/go/%E6%A0%87%E5%87%86%E5%BA%93/go_%E6%A0%87%E5%87%86%E5%BA%93log">标准库log</a></li>
</ul>
<!-- ##
## .NET

* [C# 入门基础合集](/dotnet/基础合集)
* [C# 面向对象](/dotnet/面向对象)
* [C# 数据结构](/dotnet/数据结构)
* [C# 泛型技术](/dotnet/泛型技术)
* [C# 反射技术](/dotnet/反射技术)
* [C# 多线程开发](/dotnet/多线程开发)
* [C# 多线程之线程同步技术](/dotnet/多线程之线程同步技术)
* [C# 委托和事件详解](/dotnet/委托和事件详解)
* [C# 并行编程](/dotnet/并行编程)
* [C# 异步编程](/dotnet/异步编程)
* [C# 值类型和引用类型内存分配](/dotnet/值类型和引用类型的内存分配)
* [1.1 DataProtection简介](/dotnet/1.1DataProtection简介)
* [1.2 DataProtection方法介绍](/dotnet/1.2DataProtection方法介绍)
* [1.3 落地实践及多环境调试](/dotnet/1.3落地实践及多环境调试)
* [1.4 UserSecrets](/dotnet/1.4UserSecrets)
* [1.5 数据保护方案](/dotnet/1.5基于DataProtection的数据保护方案)
* [1.6 集成AzureDevops](/dotnet/1.6方案实践及集成AzureDevops管道)


ELK Stack

* [ElastaticSearch入门](/elk/1.1ElastaticSearch入门)
* [ElastaticSearch配置](/elk/1.2ElastaticSearch配置)
* [使用Kibana操作ES](/elk/1.3使用Kibana操作ES)
 ## Docker

* [1.1 Docker概念及安装](/docker/1.1Docker概念及安装)
* [1.2 Docker镜像](/docker/1.2Docker镜像)
* [1.3 Docker容器](/docker/1.3Docker容器)
* [1.4 Docker仓库](/docker/1.4Docker仓库)
* [1.5 Docker数据管理](/docker/1.5Docker数据管理)
* [1.6 Docker容器四种网络模式](/docker/1.6Docker容器四种网络模式)
* [1.7 Docker高级网络配置](/docker/1.7Docker高级网络配置)
* [1.8 Dockerfile](/docker/1.8Dockerfile)
* [1.9 DockerCompose](/docker/1.9Docker三剑客之DockerCompose)
* [2.0 DockerMachine](/docker/2.0Docker三剑客之DockerMachine)
* [2.1 DockerSwarm](/docker/2.1Docker三剑客之DockerSwarm)
* [2.2 Docker常用命令](/docker/2.2Docker常用命令)
* [Portainer可视化面板](/docker/Portainer可视化面板)
* [1.6 Docker四种网络模式](/docker/1.6Docker容器网络模式)
* [1.7 Docker高级网络配置](/docker/1.7Docker高级网络配置)
* [1.8 Dockerfile](/docker/1.8Dockerfile)
* [1.9 DockerCompose](/docker/1.9DockerCompose)
* [2.0 DockerMachine](/docker/2.0DockerMachine)
* [2.1 DockerSwarm](/docker/2.1DockerSwarm)
* [2.2 Docker常用命令](/docker/2.2Docker常用命令)
* [Portainer可视化面板](/docker/Portainer可视化面板) 

## Linux

* [Centos安装](/linux/Centos安装)
* [Linux目录说明](/linux/Linux目录说明)
* [Centos网络配置](/linux/Centos网络配置)
* [Centos7升级gcc版本](/linux/Centos7升级gcc版本)
* [Linux常用命令](/linux/Linux常用命令)

## RabbitMQ

* [1.1 RabbitMQ概念及安装](/rabbitMq/1.1RabbitMQ概念及安装)
* [1.2 工作模式介绍](/rabbitMq/1.2工作模式介绍)
* [1.3 消息确认及持久化](/rabbitMq/1.3消息确认及持久化)
* [1.4 两种消费模式和QOS](/rabbitMq/1.4两种消费模式和QOS的实现)
* [1.5 Channel常见方法](/rabbitMq/1.5Channel常见方法)
* [1.6 RabbitMQ常用命令](/rabbitMq/1.6RabbitMQ常用命令)
* [1.7 RabbitMQ常见策略](/rabbitMq/1.7RabbitMQ常见策略)
* [1.8 RabbitMQ常见问题](/rabbitMq/1.8RabbitMQ常见问题)
* [1.9 RabbitMQ集群方案](/rabbitMq/1.9RabbitMQ集群方案)
* [客户端连接RabbitMQ](/rabbitMq/客户端连接RabbitMQ)

## Redis

* [1.1 NoSql概述](/redis/1.1NoSql概述)
* [1.2 Redis安装](/redis/1.2Redis安装)
* [1.3 Redis基本数据类型](/redis/1.3Redis基本数据类型)
* [1.4 Redis特殊数据类型](/redis/1.4Redis特殊数据类型)
* [1.5 Redis事务操作](/redis/1.5Redis事务操作)
* [1.6 Redis配置文件详解](/redis/1.6Redis配置文件详解)
* [1.7 Redis持久化](/redis/1.7Redis持久化)
* [1.8 Redis发布订阅](/redis/1.8Redis发布订阅)
* [1.9 Redis集群方案](/redis/1.9Redis集群方案)
* [1.10 Redis常见问题](/redis/1.10Redis常见问题)
* [客户端连接Redis](/redis/客户端连接Redis)
* [使用Docker搭建Redis集群](/redis/使用Docker搭建Redis集群)

## MicroService

* [1.1 微服务之项目搭建](/microservice/1.1微服务入门之项目搭建)
* [1.2 微服务之服务注册发现](/microservice/1.2微服务入门之服务注册与发现)
* [1.3 微服务之网关](/microservice/1.3微服务入门之网关)
* [1.4 微服务之事件总线](/microservice/1.4微服务入门之事件总线)
* [1.5 微服务之DockerCompose](/microservice/1.5微服务入门之DockerCompose)
* [Consul服务注册发现](/microservice/Consul服务注册发现)

## Test

* [单元测试](/test/单元测试)
* [集成测试](/test/集成测试)
* [压力测试k6](/test/压力测试k6)
* [自动化UI测试](/test/自动化UI测试) -->

</div>


<script src="/js/book-menu.js"></script>

  </div>

  <div class="sidebar-toggle" onclick="sidebar_toggle()" onmouseover="add_inner()" onmouseleave="remove_inner()">
  <div class="sidebar-toggle-inner"></div>
</div>

<script>
function add_inner() {
  let inner = document.querySelector('.sidebar-toggle-inner')
  inner.classList.add('show')  
}

function remove_inner() {
  let inner = document.querySelector('.sidebar-toggle-inner')
  inner.classList.remove('show')
}

function sidebar_toggle() {
    let sidebar_toggle = document.querySelector('.sidebar-toggle')
    let sidebar = document.querySelector('.book-sidebar')
    let content = document.querySelector('.off-canvas-content')
    if (sidebar_toggle.classList.contains('extend')) { // show
        sidebar_toggle.classList.remove('extend')
        sidebar.classList.remove('hide')
        content.classList.remove('extend')
    }
    else { // hide
        sidebar_toggle.classList.add('extend')
        sidebar.classList.add('hide')
        content.classList.add('extend')
    }
}
</script>

  <div class="off-canvas-content">
    <div class="columns">
      <div class="column col-10 col-lg-12">
        <div class="book-navbar">
          <!-- For Responsive Layout -->

<header class="navbar">
  <section class="navbar-section">
    <a onclick="open_sidebar()">
      <i class="icon icon-menu"></i>
    </a>
  </section>
</header>

        </div>
        <div class="book-content">
          <div class="book-post">
  <p>函数指：可重复使用的、用于执行指定任务的代码块。Go语言中支持函数、匿名函数和闭包，函数在Go语言中属于“一等公民”。</p>
<h1 id="函数定义">函数定义</h1>
<p>函数定义格式如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> 函数名<span class="params">(参数)</span></span>(返回值)&#123;</span><br><span class="line">    函数体</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意：</p>
<ul>
<li>函数名：由字母、数字、下划线组成。但函数名的第一个字母不能是数字。同一个包内函数名也称不能重名</li>
<li>参数：参数由参数变量和参数变量的类型组成，多个参数之间使用 <code>,</code> 分隔</li>
<li>返回值：返回值由返回值变量和其变量类型组成，也可以只写返回值的类型，多个返回值必须用 <code>()</code> 包裹，并用 <code>,</code> 分隔</li>
<li>函数体：实现指定功能的代码块</li>
</ul>
<p>比如：定义求两数之和的函数：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">func1</span><span class="params">(x <span class="type">int</span>, y <span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> x + y</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>函数的参数和返回值都是可选的，比如：可以定义无参数无返回值的函数：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">func2</span><span class="params">()</span></span> &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;hello world&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="函数调用">函数调用</h1>
<p>通过 <code>函数名()</code> 的方式调用函数，比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	sum := func1(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">    func2()</span><br><span class="line">	fmt.Println(sum)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="参数">参数</h1>
<h2 id="类型简写">类型简写</h2>
<p>函数的参数中如果相邻变量的类型相同，则可以省略类型，比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">func4</span><span class="params">(x, y <span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> x + y</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="可变参数">可变参数</h2>
<p>可变参数是指函数的参数数量不固定。可变参数通过在参数名后加<code>...</code>标识。比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">func5</span><span class="params">(x ...<span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	sum := <span class="number">0</span></span><br><span class="line">	<span class="keyword">for</span> _, v := <span class="keyword">range</span> x &#123;</span><br><span class="line">		sum += v</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> sum</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>调用：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a := func5(<span class="number">1</span>)</span><br><span class="line">b := func5(<span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line">c := func5(<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>)</span><br><span class="line">fmt.Println(a, b, c) <span class="comment">// 1 5 9</span></span><br></pre></td></tr></table></figure>
<p>固定参数搭配可变参数使用时，可变参数要放在固定参数的后面，比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">func6</span><span class="params">(x <span class="type">int</span>, y ...<span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">for</span> _, v := <span class="keyword">range</span> y &#123;</span><br><span class="line">		x += v</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> x</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>本质上，函数的可变参数是通过切片实现的。</p>
<h1 id="返回值">返回值</h1>
<p>Go语言中通过  <code>return</code>  关键字向外输出返回值。</p>
<h2 id="多返回值">多返回值</h2>
<p>Go语言中函数支持多返回值，函数如果有多个返回值时必须用  <code>()</code>  将所有返回值包裹起来。比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">func7</span><span class="params">(x, y <span class="type">int</span>)</span></span> (<span class="type">int</span>, <span class="type">int</span>) &#123;</span><br><span class="line">	sum := x + y</span><br><span class="line">	sub := x - y</span><br><span class="line">	<span class="keyword">return</span> sum, sub</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="返回值命名">返回值命名</h2>
<p>函数定义时可以给返回值命名，并在函数体中直接使用这些变量，最后通过 <code>return</code> 关键字返回。比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">func8</span><span class="params">(x, y <span class="type">int</span>)</span></span> (sum, sub <span class="type">int</span>) &#123;</span><br><span class="line">	sum = x + y</span><br><span class="line">	sub = x - y</span><br><span class="line">	<span class="comment">// 这里可以直接return,不需要指定sum和sub</span></span><br><span class="line">	<span class="keyword">return</span> sum, sub</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="返回值补充">返回值补充</h2>
<p>当函数返回值类型为 <code>slice</code> 时，<code>nil</code> 可以看做是一个有效的 <code>slice</code> ，没必要显式返回一个长度为0的切片。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">func9</span><span class="params">(x <span class="type">string</span>)</span></span> []<span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">if</span> x == <span class="string">&quot;&quot;</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">nil</span> <span class="comment">// 没必要返回[]int&#123;&#125;</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> []<span class="type">int</span>&#123;<span class="number">0</span>&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="变量作用域">变量作用域</h1>
<h2 id="全局变量-v2">全局变量</h2>
<p>全局变量是定义在函数外部的变量，在程序整个运行周期内都有效。 在函数中可以访问到全局变量。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;fmt&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义全局变量value</span></span><br><span class="line"><span class="keyword">var</span> value <span class="type">int64</span> = <span class="number">10</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">test</span><span class="params">()</span></span> &#123;</span><br><span class="line">	fmt.Printf(<span class="string">&quot;value=%d\n&quot;</span>, value) <span class="comment">// 函数中可以访问全局变量value</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	test() <span class="comment">// value=10</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="局部变量">局部变量</h2>
<p>局部变量分为两种：</p>
<ul>
<li>函数内定义的变量无法在该函数外使用</li>
<li>如果局部变量和全局变量重名，优先访问局部变量</li>
<li>语句块定义的变量，只在 <code>if</code>、<code>for</code>、<code>switch</code> 语句内有效</li>
</ul>
<h1 id="函数类型与变量">函数类型与变量</h1>
<h2 id="定义函数类型">定义函数类型</h2>
<p>可以使用 <code>type</code> 关键字来定义一个函数类型，比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> calculation <span class="function"><span class="keyword">func</span><span class="params">(<span class="type">int</span>, <span class="type">int</span>)</span></span> <span class="type">int</span></span><br></pre></td></tr></table></figure>
<p>上面定义了一个 <code>calculation</code> 类型，它是一种函数类型，接收两个 <code>int</code> 类型的参数并且返回一个 <code>int</code> 类型的返回值。凡是满足这个条件的函数都是 <code>calculation</code> 类型的函数，例如下面的 <code>sum</code> 和  <code>sub</code> 都是 <code>calculation</code> 类型。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// calculation类型的函数sum</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sum</span><span class="params">(x, y <span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> x + y</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// calculation类型的函数sub</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sub</span><span class="params">(x, y <span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> x - y</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>sum</code> 和 <code>sub</code> 都能赋值给 <code>calculation</code> 类型的变量。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> calc1 calculation = sum</span><br><span class="line"><span class="keyword">var</span> calc2 calculation = sub</span><br></pre></td></tr></table></figure>
<h2 id="函数类型变量">函数类型变量</h2>
<p>可以声明函数类型的变量并且为该变量赋值：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> a calculation = sum</span><br><span class="line">	fmt.Printf(<span class="string">&quot;type of a:%T\n&quot;</span>, a) <span class="comment">// type of c:main.calculation</span></span><br><span class="line">	fmt.Println(a(<span class="number">1</span>, <span class="number">2</span>))            <span class="comment">// 像调用sum一样调用a</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">var</span> b calculation = sub</span><br><span class="line">	fmt.Printf(<span class="string">&quot;type of b:%T\n&quot;</span>, b) <span class="comment">// type of c:main.calculation</span></span><br><span class="line">	fmt.Println(b(<span class="number">1</span>, <span class="number">2</span>))            <span class="comment">// 像调用sub一样调用b</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">type</span> of a:main.calculation</span><br><span class="line">3</span><br><span class="line"><span class="built_in">type</span> of b:main.calculation</span><br><span class="line">-1</span><br></pre></td></tr></table></figure>
<h1 id="高阶函数">高阶函数</h1>
<h2 id="函数作为参数">函数作为参数</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 将函数作为参数传递，该函数接收两个int类型变量x/y,一个函数参数sum。</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">functionAsArgument</span><span class="params">(x, y <span class="type">int</span>, sum <span class="keyword">func</span>(<span class="type">int</span>, <span class="type">int</span>)</span></span> <span class="type">int</span>) <span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> sum(x, y)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">func1</span><span class="params">(x <span class="type">int</span>, y <span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> x + y</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">functionAsArgumentTest</span><span class="params">()</span></span> &#123;</span><br><span class="line">	ret2 := functionAsArgument(<span class="number">10</span>, <span class="number">20</span>, func1)</span><br><span class="line">	fmt.Println(ret2) <span class="comment">//30</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="函数作为返回值">函数作为返回值</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 接收一个切片参数patients,返回一个函数</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">functionAsTheReturnValue</span><span class="params">(patients []<span class="type">string</span>)</span></span> <span class="function"><span class="keyword">func</span><span class="params">(<span class="type">string</span>)</span></span> <span class="type">bool</span> &#123;</span><br><span class="line">	<span class="comment">// 定义匿名函数并返回</span></span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">func</span><span class="params">(name <span class="type">string</span>)</span></span> <span class="type">bool</span> &#123;</span><br><span class="line">		<span class="keyword">for</span> _, soul := <span class="keyword">range</span> patients &#123;</span><br><span class="line">			<span class="keyword">if</span> soul == name &#123;</span><br><span class="line">				<span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">functionAsTheReturnValueTest</span><span class="params">()</span></span> &#123;</span><br><span class="line">	testValue := []<span class="type">string</span>&#123;<span class="string">&quot;a&quot;</span>, <span class="string">&quot;b&quot;</span>, <span class="string">&quot;c&quot;</span>, <span class="string">&quot;d&quot;</span>, <span class="string">&quot;e&quot;</span>, <span class="string">&quot;f&quot;</span>&#125;</span><br><span class="line">	result := functionAsTheReturnValue(testValue)</span><br><span class="line">	<span class="comment">// 调用筛选器函数获取字母是否已存在</span></span><br><span class="line">	fmt.Println(result(<span class="string">&quot;a&quot;</span>))  <span class="comment">// true</span></span><br><span class="line">	fmt.Println(result(<span class="string">&quot;ff&quot;</span>)) <span class="comment">// false</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="匿名函数">匿名函数</h1>
<p>已经知道函数可以作为返回值，但是在Go语言函数内部不能再像之前那样定义函数了，只能定义匿名函数。匿名函数就是没有函数名的函数，匿名函数的定义格式如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span><span class="params">(参数)</span></span>(返回值)&#123;</span><br><span class="line">    函数体</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>匿名函数因为没有函数名，所以没办法像普通函数那样调用，所以匿名函数需要保存到某个变量或者作为立即执行函数:</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">anonymousFunc</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="comment">// 将匿名函数保存到变量</span></span><br><span class="line">	add := <span class="function"><span class="keyword">func</span><span class="params">(x, y <span class="type">int</span>)</span></span> &#123;</span><br><span class="line">		fmt.Println(x + y)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 通过变量调用匿名函数</span></span><br><span class="line">	add(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 匿名函数作为立即执行函数,一般用于匿名函数只用于一次的情况下就不需要再指定变量存储</span></span><br><span class="line">	<span class="function"><span class="keyword">func</span><span class="params">(x, y <span class="type">int</span>)</span></span> &#123;</span><br><span class="line">		fmt.Println(x - y)</span><br><span class="line">	&#125;(<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>匿名函数多用于实现回调函数和闭包。</p>
<h1 id="闭包">闭包</h1>
<p>闭包是函数式编程语言中的概念。指内层函数引用了外层函数中的变量或称为引用了自由变量（全局变量）的函数，其返回值也是一个函数。在Go语言中可以理解为<strong>匿名函数与其所引用环境的组合</strong>。</p>
<p>闭包只是在形式和表现上像函数，但实际上不是函数。函数是一些可执行的代码，这些代码在函数被定义后就确定了，不会在执行时发生变化，所以一个函数只有一个实例。闭包在运行时可以有多个实例，不同的引用环境和相同的函数组合可以产生不同的实例。所谓引用环境是指在程序执行中的某个点所有处于活跃状态的约束所组成的集合。其中的约束是指一个变量的名字和其所代表的对象之间的联系。那么为什么要把引用环境与函数组合起来呢？这主要是因为在支持嵌套作用域的语言中，有时不能简单直接地确定函数的引用环境。这样的语言一般具有这样的特性</p>
<blockquote>
<p>函数是一等公民（First-class value），即函数可以作为另一个函数的返回值或参数，还可以作为一个变量的值。 函数可以嵌套定义，即在一个函数内部可以定义另一个函数。</p>
</blockquote>
<p>比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">add</span><span class="params">()</span></span> <span class="function"><span class="keyword">func</span><span class="params">(<span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">var</span> x <span class="type">int</span></span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">func</span><span class="params">(y <span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">		x += y</span><br><span class="line">		<span class="keyword">return</span> x</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">addTest</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> f = add()</span><br><span class="line">	fmt.Println(f(<span class="number">10</span>)) <span class="comment">//10</span></span><br><span class="line">	fmt.Println(f(<span class="number">20</span>)) <span class="comment">//30</span></span><br><span class="line">	fmt.Println(f(<span class="number">30</span>)) <span class="comment">//60</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述代码中</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> x <span class="type">int</span></span><br><span class="line"><span class="keyword">return</span> <span class="function"><span class="keyword">func</span><span class="params">(y <span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	x += y</span><br><span class="line">	<span class="keyword">return</span> x</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时 <code>f</code>  就是一个闭包，<code>f</code> 不仅仅是存储了一个函数的返回值，同时存储了一个闭包的状态。该状态会一直存在外部被赋值的变量 <code>f</code> 中，直到 <code>f</code> 被销毁，整个闭包才被销毁。</p>
<p>再看一个例子：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">add2</span><span class="params">(x <span class="type">int</span>)</span></span> <span class="function"><span class="keyword">func</span><span class="params">(<span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">func</span><span class="params">(y <span class="type">int</span>)</span></span> <span class="type">int</span> &#123;</span><br><span class="line">		x += y</span><br><span class="line">		<span class="keyword">return</span> x</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">add2Test</span><span class="params">()</span></span> &#123;</span><br><span class="line">	<span class="keyword">var</span> f = add2(<span class="number">10</span>)</span><br><span class="line">	fmt.Println(f(<span class="number">10</span>)) <span class="comment">//20</span></span><br><span class="line">	fmt.Println(f(<span class="number">20</span>)) <span class="comment">//40</span></span><br><span class="line">	fmt.Println(f(<span class="number">30</span>)) <span class="comment">//70</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>函数 <code>add2</code> 返回了一个函数，返回的这个函数就是一个闭包。这个函数本身中没有定义变量 <code>x</code> 的，而是引用了它所在的环境（函数 <code>add2</code>）中的变量 <code>x</code>。</p>
<p>每调用一次函数 <code>add2</code>，就形成了一个新的环境，对应的闭包中，函数都是同一个函数，环境却是引用不同的环境。变量 <code>x</code> 是函数 <code>add2 </code>中的局部变量，这个变量不会在函数 <code>add2 </code> 的栈中分配，因为函数 <code>add2</code> 返回后，对应的栈就失效了，<code>add2</code> 返回的那个函数中变量 <code>x</code> 就引用了一个失效的位置。所以闭包的环境中引用的变量不能够在栈上分配。</p>
<h1 id="闭包的陷阱">闭包的陷阱</h1>
<p>TODO</p>
<h1 id="defer-语句">defer 语句</h1>
<p>Go语言中 <code>defer</code> 语句会将其后面跟随的语句进行延迟处理。在 <code>defer</code> 归属的函数即将返回时，将延迟处理的语句按 <code>defer</code> 定义的逆序执行。先被 <code>defer</code> 的语句最后被执行，最后被 <code>defer</code> 的语句，最先被执行。比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// defer将后面的语句延迟到函数即将退出时逆序执行,一般常用于资源释放</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">deferTest</span><span class="params">()</span></span> &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;start&quot;</span>)</span><br><span class="line">	<span class="keyword">defer</span> fmt.Println(<span class="string">&quot;...&quot;</span>)</span><br><span class="line">	fmt.Println(<span class="string">&quot;end&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">start</span><br><span class="line">end</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
<p>函数中存在多个 <code>defer</code> 时,逆序执行后进先出，比如：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">deferTest2</span><span class="params">()</span></span> &#123;</span><br><span class="line">	fmt.Println(<span class="string">&quot;start&quot;</span>)</span><br><span class="line">	<span class="keyword">defer</span> fmt.Println(<span class="string">&quot;1111&quot;</span>)</span><br><span class="line">	<span class="keyword">defer</span> fmt.Println(<span class="string">&quot;2222&quot;</span>)</span><br><span class="line">	<span class="keyword">defer</span> fmt.Println(<span class="string">&quot;3333&quot;</span>)</span><br><span class="line">	fmt.Println(<span class="string">&quot;end&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">start</span><br><span class="line">end  </span><br><span class="line">3333</span><br><span class="line">2222</span><br><span class="line">1111</span><br></pre></td></tr></table></figure>
<p>由于 <code>defer </code> 语句延迟调用的特性，所以 <code>defer</code> 语句一般用于处理资源释放问题。比如：资源清理、文件关闭、解锁及记录时间等。</p>
<h1 id="defer-执行时机">defer 执行时机</h1>
<p>Go语言的函数中 <code>return</code> 语句在底层并不是原子操作，它分为两步：</p>
<ol>
<li>给返回值赋值</li>
<li>执行 <code>RET</code> 指令</li>
</ol>
<p><code>defer</code> 语句执行的时机是在返回值赋值操作后，执行 <code>RET</code> 指令前。如下图所示：</p>
<p><img src="https://www.liwenzhou.com/images/Go/func/defer.png" alt="defer执行时机"></p>

</div>


  <div class="book-comments">
    




  </div>



<script src="/js/book-post.js"></script>

        </div>
      </div>
      <div class="column col-2 hide-lg">
        <div class="book-post-info">
  
    <div class="book-post-meta">

  <div class="author">

    <!-- Author image -->
    <div class="author-img">
      
        <figure
          class="avatar avatar-lg"
          data-initial="W"
          style="background-color: #3b4351;">
        </figure>
      
    </div>

    <!-- Author title -->
    <div class="author-title">
      <div>WangPengLiang</div>
      <div>2022-03-30</div>
    </div>
  </div>

  

  <div class="divider"></div>
</div>
  

  <div class="book-tocbot">
</div>
<div class="book-tocbot-menu">
  <a class="book-toc-expand" onclick="expand_toc()">Expand all</a>
  <a onclick="go_top()">Back to top</a>
  <a onclick="go_bottom()">Go to bottom</a>
</div>


<script src="/js/book-toc.js"></script>

</div>
      </div>
    </div>
  </div>
  
  <a class="off-canvas-overlay" onclick="hide_canvas()"></a>
</div>

</body>
</html>


<script src="/js/book.js"></script>
